# 第一阶段：基础依赖安装（添加NPM环境验证）
FROM node:16-alpine AS frontend-deps
WORKDIR /app
RUN echo "当前构建阶段：前端依赖安装" && \
    echo "NPM镜像源：$(npm config get registry)" && \
    npm --version
COPY web/package.json web/package-lock.json* ./web/
RUN cd web && \
    echo "开始安装依赖..." && \
    npm list --depth=0 2>&1 | tee pre_install_deps.log && \
    npm install --legacy-peer-deps --prefer-offline --no-audit && \
    echo "已安装依赖树：" && \
    npm ls --depth=0

# 第二阶段：前端构建（添加构建路径验证）
FROM frontend-deps AS frontend-builder
COPY web ./web
RUN echo "当前构建阶段：前端代码构建" && \
    echo "工作目录结构：" && \
    ls -lR && \
    cd web && \
    npm run build && \
    echo "构建产物验证：" && \
    du -sh dist && \
    find dist -type f -print | xargs ls -lh

# 第三阶段：Go程序构建（添加编译信息打印）
FROM golang:1.17-alpine AS backend-builder
WORKDIR /app
RUN echo "当前构建阶段：后端编译" && \
    echo "Go版本：$(go version)" && \
    echo "系统架构：$(uname -m)" && \
    echo "当前目录：$(pwd)"
COPY . .
RUN echo "源代码结构：" && \
    find . -type f -print | xargs ls -lh && \
    CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -v -o main . 2>&1 | tee build.log

# 第四阶段：生产镜像（添加运行时验证）
FROM alpine:3.13
RUN echo "初始化生产镜像" && \
    echo "镜像时区：$(date +%Z)" && \
    echo "系统版本：" && \
    cat /etc/os-release

WORKDIR /app
COPY --from=frontend-builder /app/web/dist ./web/dist
COPY --from=backend-builder /app/main .
COPY index.html .
COPY docker/nginx.conf /etc/nginx/nginx.conf

RUN echo "最终镜像文件清单：" && \
    ls -lR /app && \
    echo "Nginx配置检查：" && \
    nginx -t -c /etc/nginx/nginx.conf && \
    echo "二进制文件验证：" && \
    file main && \
    ldd main || echo "静态编译验证通过"

CMD ["/app/main"]